package io.github.heollhai.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: lmf
 * @Create: 2024/7/9 16:31
 * Description:
 */
@Slf4j
public class JWTUtil {
    /**
     * 密钥
     */
    private static final String SECRET = "rsk.098123.login";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "rsk.class.login";
    /**
     * subject
     */
    private static final String SUBJECT = "rsk.class.user.login";

    /**
     * 根据用户信息生成token
     */
    public static String createToken(String token) {
        String timestamp = DateUtil.getCurrentLocalDateStr(DateUtil.DATE_TIME_FORMAT_2);
        return Jwts.builder()
                .setSubject(SUBJECT)
                .claim("token",  token)
                .claim("timestamp", timestamp)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }


    /**
     * 解密token
     */
    public static String checkJwt(String token) {
        try {

            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();

            if (claims != null) {
                return claims.get("token", String.class);
            }

            return null;
        } catch (Exception e) {
            log.error("token解析失败");
            return null;
        }
    }
}
